import { Card, Form, Input, Select, Spin } from 'antd'
import React, { useCallback, useContext, useState } from 'react'
import PubSub from 'pubsub-js'
import VersionPageTable from '../../VersionPageTable'
import FlowContext from '@/pages/Flow/FlowContext'
import request from '@/utils/request'
import Space from '@/components/Space'
import ComboGrid from '@/pages/Transformer/components/ComboGrid'

function TransformPanel({ form, node, update, input }) {
  const { getFieldDecorator, validateFields } = form
  const { label, nodeCode, nodeId, sourceMessageFormat, targetMessageFormat, nodeVersionId } = node

  const { state } = useContext(FlowContext)
  const { processId, versionId } = state
  const [loading, setLoading] = useState(false)
  const isEdit = !!nodeId

  const [readOnly, setReadOnly] = useState(isEdit)
  const [isNew, setNew] = useState(true)

  const onSave = useCallback(() => {
    validateFields((err, values) => {
      if (!err) {
        if (!isNew) {
          const transformer = values.transformer[0]
          update({
            nodeId: transformer.transformId,
            label: transformer.transformName,
            nodeCode: transformer.transformCode,
            sourceMessageFormat: transformer.sourceMessageFormat,
            targetMessageFormat: transformer.targetMessageFormat,
          })
          setReadOnly(true)
          setNew(true)
          PubSub.publish(`nodeSave_${processId}_${versionId}`)
          return
        }
        setLoading(true)
        if (isEdit) {
          request
            .post('/transform/updateTransform', {
              data: { ...values, transformId: nodeId },
            })
            .then(() => {
              update({
                label: values.transformName,
                nodeCode: values.transformCode,
                sourceMessageFormat: values.sourceMessageFormat,
                targetMessageFormat: values.targetMessageFormat,
              })
              setReadOnly(true)
              PubSub.publish(`nodeSave_${processId}_${versionId}`)
            })
            .finally(() => {
              setLoading(false)
            })
        }
        else {
          request
            .post('/transform/createTransform', {
              data: { ...values, processId },
            })
            .then(({ transformId }) => {
              update({
                nodeId: transformId,
                label: values.transformName,
                nodeCode: values.transformCode,
                sourceMessageFormat: values.sourceMessageFormat,
                targetMessageFormat: values.targetMessageFormat,
              })
              setReadOnly(true)
              PubSub.publish(`nodeSave_${processId}_${versionId}`)
            })
            .finally(() => {
              setLoading(false)
            })
        }
      }
    })
  }, [isEdit, isNew, nodeId, processId, update, validateFields, versionId])

  return (
    <Card
      type="inner"
      size="small"
      title="转换器"
      bordered={false}
      extra={
        readOnly
          ? (
          <a onClick={() => setReadOnly(false)}>编辑</a>
            )
          : (
          <Space divider="vertical">
            {!nodeId
              && (isNew
                ? (
                <a onClick={() => setNew(false)}>关联</a>
                  )
                : (
                <a onClick={() => setNew(true)}>新建</a>
                  ))}
            <a onClick={onSave}>保存</a>
          </Space>
            )
      }
    >
      <Spin spinning={loading}>
        {isNew
          ? (
          <Form>
            <Form.Item label="转换器名称">
              {getFieldDecorator('transformName', {
                initialValue: label,
                rules: [
                  {
                    required: true,
                    message: '转换器名称不能为空',
                  },
                ],
              })(<Input disabled={readOnly} placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="转换器编码">
              {getFieldDecorator('transformCode', {
                initialValue: nodeCode,
                rules: [
                  {
                    required: true,
                    message: '转换器编码不能为空',
                  },
                ],
              })(<Input disabled={readOnly} placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="源报文格式">
              {getFieldDecorator('sourceMessageFormat', {
                initialValue: sourceMessageFormat,
                rules: [
                  {
                    required: true,
                    message: '源报文格式不能为空',
                  },
                ],
              })(
                <Select disabled={readOnly || isEdit}>
                  <Select.Option value="JSON">JSON</Select.Option>
                  <Select.Option value="XML">XML</Select.Option>
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="目标报文格式">
              {getFieldDecorator('targetMessageFormat', {
                initialValue: targetMessageFormat,
                rules: [
                  {
                    required: true,
                    message: '目标报文格式不能为空',
                  },
                ],
              })(
                <Select disabled={readOnly || isEdit}>
                  <Select.Option value="JSON">JSON</Select.Option>
                  <Select.Option value="XML">XML</Select.Option>
                </Select>,
              )}
            </Form.Item>
          </Form>
            )
          : (
          <Form>
            <Form.Item label="选择转换器">
              {getFieldDecorator('transformer', {
                rules: [
                  {
                    required: true,
                    message: '请选择转换器',
                  },
                ],
              })(
                <ComboGrid
                  url="/transform/listTransforms"
                  method="get"
                  popupStyle={{ width: 600 }}
                  placeholder="--请选择--"
                  searchPlaceholder="请输入"
                  destroyPopupOnHide
                  label="transformName"
                  rowKey="transformId"
                  pick="radio"
                  searchableColumns={['transformName', 'transformCode']}
                  columns={[
                    {
                      title: '转换器名称',
                      dataIndex: 'transformName',
                      ellipsis: true,
                    },
                    {
                      title: '转换器编码',
                      dataIndex: 'transformCode',
                      ellipsis: true,
                    },
                    {
                      title: '源报文格式',
                      dataIndex: 'sourceMessageFormat',
                      ellipsis: true,
                    },
                    {
                      title: '目标报文格式',
                      dataIndex: 'targetMessageFormat',
                      ellipsis: true,
                    },
                  ]}
                />,
              )}
            </Form.Item>
          </Form>
            )}

        {isEdit ? (
          <VersionPageTable
            style={{ marginTop: '16px' }}
            element="transform"
            elementIdKey="transformId"
            elementId={nodeId}
            elementVersionId={nodeVersionId}
            routePrefix="transformer"
            params={
              input && input.branch === 'VALIDATE_FAILURE' ? { sourceType: input.branch } : {}
            }
            readOnly={state.readOnly}
            onValidVersion={(nodeVersionId) => {
              update({ nodeVersionId })
              PubSub.publish(`nodeSave_${processId}_${versionId}`)
            }}
            // onFirstLoading={data => {
            //   const validVersion = data.find(item => item.versionState === 1);
            //   if (validVersion) {
            //     update({ nodeVersionId: validVersion.versionId });
            //     PubSub.publish(`nodeSave_${processId}_${versionId}`);
            //   }
            // }}
          />
        ) : null}
      </Spin>
    </Card>
  )
}

export default Form.create()(TransformPanel)
